package com.keyinong.caizhengting.adapter;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.ImageUtils;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.tools.Utility;
import com.keyinong.caizhengting.entity.GuigeEntity;
import com.keyinong.caizhengting.entity.MycollectEntity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 我的收藏适配器
 */

public class MycollectAdapter extends BaseAdapter {
    Context context;
    ArrayList<MycollectEntity> mycollecyList;
    HttpTools httpTools = null;

    public MycollectAdapter(Context context, ArrayList<MycollectEntity> mycollecyList) {
        super();
        this.context = context;
        this.mycollecyList = mycollecyList;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mycollecyList.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return mycollecyList.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHandle handle;
        if (view == null) {
            handle = new ViewHandle();
            view = LayoutInflater.from(context).inflate(R.layout.item_mycollect, null);
            handle.iv_shangpin = (ImageView) view.findViewById(R.id.imageView1);
            handle.tv_shangpinming = (TextView) view.findViewById(R.id.tv_shangpinming5);
            handle.tv_content = (TextView) view.findViewById(R.id.tv_content5);
            handle.tv_price = (TextView) view.findViewById(R.id.tv_price5);
            handle.ib_shoucang = (ImageButton) view.findViewById(R.id.ib_shoucang5);
            handle.ib_add = (ImageButton) view.findViewById(R.id.ib_add5);
            handle.ib_less = (ImageButton) view.findViewById(R.id.ib_less5);
            handle.et_amout = (EditText) view.findViewById(R.id.et_amount5);
            handle.tv_guige = (TextView) view.findViewById(R.id.tv_guige);
//			handle.tv_guige.setVisibility(View.GONE);		
            view.setTag(handle);
        } else {
            handle = (ViewHandle) view.getTag();
        }
        handle.tv_shangpinming.setText(mycollecyList.get(position).getName());
        handle.tv_content.setText(mycollecyList.get(position).getContent());
        handle.tv_price.setText(mycollecyList.get(position).getPrice());
        handle.et_amout.setText(mycollecyList.get(position).getAmount());
        if (!mycollecyList.get(position).getArraylength().equals("0")) {
            handle.tv_guige.setVisibility(View.VISIBLE);
            handle.et_amout.setVisibility(View.GONE);
            handle.ib_add.setVisibility(View.GONE);
            handle.ib_less.setVisibility(View.GONE);
        } else if (mycollecyList.get(position).getArraylength().equals("0")) {
            handle.tv_guige.setVisibility(View.GONE);
            handle.et_amout.setVisibility(View.VISIBLE);
            handle.ib_add.setVisibility(View.VISIBLE);
            handle.ib_less.setVisibility(View.VISIBLE);
        }
        handle.tv_guige.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                guigedialog(position);
            }
        });
        ImageUtils.displayImage(context,
                (mycollecyList.get(position).getImage()).replace("w/60", "w/120"),
                handle.iv_shangpin, R.drawable.wupian1);
        /**取消收藏*/
        handle.ib_shoucang.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                cancle(position);
//				SharedPreferences sp = context.getSharedPreferences("spReg",
//						Context.MODE_PRIVATE);
//				String token = sp.getString("data", "");
//				if (httpTools == null) {
//					httpTools = new HttpTools(context);
//				}
//				httpTools.cancelcollect(token, mycollecyList.get(position).getId(),
//						new JsonHttpResponseHandler() {
//
//							@Override
//							public void onSuccess(int statusCode, Header[] headers,
//									JSONObject response) {
//								super.onSuccess(statusCode, headers, response);
//								try {
//									boolean code = response.getBoolean("code");
//									String msg = response.getString("msg");
//									if (code == true) {
//										Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
//										mycollecyList.remove(position);
//									    notifyDataSetChanged();
////										view.setBackgroundResource(R.drawable.shouchang1);
//									} else {
//										Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
//									}
//								} catch (JSONException e) {
//									// TODO Auto-generated catch block
//									e.printStackTrace();
//								}
//							}
//
//						});
            }
        });
        /**加购物车*/
        handle.ib_add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (NetWorkUtil.isNetwork(context) == false) {
                    Toast.makeText(context, "当前网络不可用", 1).show();
                    return;
                }
                if ("".equals(handle.et_amout.getText().toString())) {
                    handle.et_amout.setText(0 + "");
                }
                int goodsNum = Integer.parseInt(handle.et_amout
                        .getText().toString());
                goodsNum++;
                handle.et_amout.setText(goodsNum + "");
                addgoodscat(position, handle.et_amout);
            }
        });
        handle.ib_less.setOnClickListener(new OnClickListener() {
            int goodsNum;

            @Override
            public void onClick(View v) {
                if ("".equals(handle.et_amout.getText().toString())) {
                    handle.et_amout.setText(0 + "");
                    goodsNum = 0;
                } else {
                    goodsNum = Integer.parseInt(handle.et_amout
                            .getText().toString());
                }
                if (goodsNum > 0) {
                    goodsNum--;
                }
                handle.et_amout.setText(goodsNum + "");
                addgoodscat(position, handle.et_amout);
            }
        });

//		/**购买*/
//		handle.ib_gouma.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				if (NetWorkUtil.isNetwork(context) == false) {
//					Toast.makeText(context, "当前网络不可用", Toast.LENGTH_SHORT).show();
//					return;
//				}
//				addgoodscat(position, handle.et_amout);
//			}
//
//
//		});
        return view;
    }

    private void addgoodscat(int index, EditText editText) {
        if (Integer.parseInt(editText.getText().toString()) <= 0) {
            Toast.makeText(context, "去购物车删除!", Toast.LENGTH_LONG).show();
            return;
        }
        SharedPreferences sp = context.getSharedPreferences("spReg", Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        Log.i("info", "token" + "token" + token);
        if (httpTools == null) {
            httpTools = new HttpTools(context);
        }
        httpTools.addgoodscat(token, mycollecyList.get(index).getId(), editText
                .getText().toString(), new JsonHttpResponseHandler() {
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, headers, response);
                try {
                    //							Log.i("zq",response.toString());
                    boolean code = response.getBoolean("code");
                    String msg = response.getString("msg");
                    if (code == true) {
                        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 取消收藏
     */
    private void cancle(final int index2) {

        SharedPreferences sp = context.getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        if (httpTools == null) {
            httpTools = new HttpTools(context);
        }
        httpTools.cancelcollect(token, mycollecyList.get(index2).getId(),
                new JsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            if (code == true) {
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                                mycollecyList.remove(index2);
                                notifyDataSetChanged();
//								view.setBackgroundResource(R.drawable.shouchang1);
                            } else {
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                });

    }

    /**
     * 选择规格dialog
     */
    private void guigedialog(int index) {
        final ArrayList<GuigeEntity> guigeList;
        final Dialog dialogli = new Dialog(context);
        dialogli.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = LayoutInflater.from(context).inflate(
                R.layout.dialog_guige, null);
        final ListView list_dailogAddress = (ListView) view
                .findViewById(R.id.lv_guige);
        dialogli.setContentView(view);
        dialogli.show();
        list_dailogAddress.requestFocus();
        guigeList = new ArrayList<GuigeEntity>();
        SharedPreferences sp = context.getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        if (httpTools == null) {
            httpTools = new HttpTools(context);
        }
        httpTools.getProductdetail(token, mycollecyList.get(index).getId(),
                new JsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            Log.i("info", response.toString());
                            if (code == true) {
                                JSONObject object = response.getJSONObject("data");
                                JSONArray array = object.getJSONArray("specs");
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject object1 = array.getJSONObject(i);
                                    String id = object1.getString("id");
                                    String name = object1.getString("name");
                                    String price = object1.getString("price");
                                    String amount = object1.getString("amount");
                                    guigeList.add(new GuigeEntity(id, name, amount, price));
//							Log.i("info", "111");
                                }
                                GuigeAdapter adapter = new GuigeAdapter(
                                        context, guigeList);
                                list_dailogAddress.setAdapter(adapter);
                                Utility.setListViewHeightBasedOnChildren(list_dailogAddress);
                            } else {
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                });

    }


    class ViewHandle {
        /**
         * 图片
         */
        ImageView iv_shangpin;
        /**
         * 商品名
         */
        TextView tv_shangpinming;
        /**
         * 说明
         */
        TextView tv_content;
        /**
         * 价格
         */
        TextView tv_price;
        /**
         * 取消收藏
         */
        ImageButton ib_shoucang;
        /**
         * 加
         */
        ImageButton ib_add;
        /**
         * 减
         */
        ImageButton ib_less;
        /**
         * 数量
         */
        EditText et_amout;
        /**
         * 选择规格
         */
        TextView tv_guige;
    }
}
